package com.czk.netty.web;

import com.czk.netty.server.NettyServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import java.net.InetSocketAddress;

/**
 * 实现CommandLineRunner
 * 在ioc启动完成后实现回调
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/21 11:43
 */
@SpringBootApplication
@ComponentScan("com.czk.netty")
public class NettyApplication implements CommandLineRunner {
    @Value("${netty.host}")
    private String host;
    @Value("${netty.port}")
    private int port;
    @Autowired
    private NettyServer nettyServer;

    @Override
    public void run(String... args) throws Exception {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        // 启动服务器
        ChannelFuture channelFuture = nettyServer.bind(inetSocketAddress);
        // 这个方法的意思就是在jvm中增加一个关闭的钩子，当jvm关闭的时候，会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子，当系统执行完这些钩子后，
        // jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。
        Runtime.getRuntime().addShutdownHook(new Thread(() -> nettyServer.destroy()));
        //
        channelFuture.channel().closeFuture().syncUninterruptibly();
    }

    public static void main(String[] args) {
        SpringApplication.run(NettyApplication.class, args);
    }
}
